package com.cnpinxi.service;

import com.cnpinxi.dao.CommissionMapper;
import com.cnpinxi.dao.ManagerCommissionMapper;
import com.cnpinxi.domain.*;
import com.cnpinxi.log.LogFactory;
import com.cnpinxi.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Baggio on 2017-12-21.
 */
@Service
public class CommissionServiceImpl implements com.cnpinxi.service.CommissionService {
    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    CommissionMapper commissionMapper;
    @Autowired
    ManagerCommissionMapper managerCommissionMapper;
    @Autowired
    DistributionConfigService distributionConfigService;
    @Autowired
    DistributionRateService distributionRateService;
    @Autowired
    UserService userService;

    @Override
    public int insertCommission(Commission record) {
        return commissionMapper.insertCommission(record);
    }

    @Override
    public int updateCommissionById(Commission record) {

        return commissionMapper.updateCommissionById(record);
    }

    @Override
    public List<Commission> selectCommissionList(Map<String, String> map) {
        String payDate = map.get("payDate");
        if (StringUtils.isNotBlank(payDate)) {
            Date date = DateUtil.strToDate(payDate, DateUtil.DATE_TIME_YYYY_MM);
            map.put("payDate", DateUtil.dateToStr(date, DateUtil.DATE));
        }
        return commissionMapper.selectCommissionList(map);
    }

    @Override
    public Commission selectCommissionById(Long tid) {
        return commissionMapper.selectCommissionById(tid);
    }

    @Override
    public void payCommission(Long tid) {

        Commission commission = selectCommissionById(tid);
        commission.setStatus(Commission.STATUS_PAYED);
        updateCommissionById(commission);
    }

    @Override
    public void commission(Order order) {

        User buyUser = userService.getUserById(order.getUserId());
      String buyOpenId=  buyUser.getOpenId();
        User sellerUser = userService.getParentUserByopenId(buyOpenId);
        if(sellerUser==null){
            logger.info("sellerUser is null ,return");
            return;
        }
        logger.info("order.getOrderItemList()=========================>>>>>>>>>>>>>>>>>>>" + order.getOrderItemList().size());
        for (OrderItem orderItem : order.getOrderItemList()
                ) {
            logger.info("orderItem.getProductEntityId()====>>>>" + orderItem.getProductEntityId());
            DistributionConfig distributionConfig = distributionConfigService.getDistributionConfigByProductEntityId(orderItem.getProductEntityId());
            if (distributionConfig != null) {
                Map<String, String> map = new HashMap<>();
                map.put("payDate", DateUtil.dateToStr(new Date(), DateUtil.DATE));
                map.put("distributionId", String.valueOf(sellerUser.getTid()));
                List<Commission> commissionList = selectCommissionList(map);
                logger.info("commissionList.size()==================>>>>>" + commissionList.size());
                Integer sellAmount = commissionList.size() + 1;

                DistributionRate distributionRate = distributionRateService.getDistributionRateBysell(sellAmount);
                Integer commissionPrice = orderItem.getPrice() * distributionRate.getRate() / 100;

                Commission commission = new Commission();
                commission.setCreateTime(new Date());
                commission.setOrderPrice(orderItem.getPrice());
                commission.setOrderDate(order.getCreateTime());
                commission.setDistributionId(sellerUser.getTid());
                commission.setDistributionName(sellerUser.getUserName());
                commission.setDistributionPhone(sellerUser.getPhone());
                commission.setDistributionOpenId(sellerUser.getOpenId());
                commission.setOrderId(order.getOrderId());
                commission.setCommission(commissionPrice);
                commission.setStatus(Commission.STATUS_UNPAYED);
                commission.setSellIndex(sellAmount);
                insertCommission(commission);
                ManagerCommission managerCommission = new ManagerCommission();
                User parentUser = userService.getParentUserByopenId(commission.getDistributionOpenId());
                if (parentUser != null) {
                    if(parentUser.getUserType()== User.USER_TYPE_ORGANIZATION){
                        logger.info("经理需要提成！");

                    managerCommission.setUserId(parentUser.getTid());
                    managerCommission.setUserName(parentUser.getUserName());
                    managerCommission.setUserOpenId(parentUser.getOpenId());
                    managerCommission.setUserPhone(parentUser.getPhone());
                    managerCommission.setOrderPrice(commission.getOrderPrice());
                    managerCommission.setCreateTime(new Date());
                    managerCommission.setSellerMonth(DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_YYYYMM));
                    managerCommission.setStatus(ManagerCommission.STATUS_UNPAYED);
                    modifyManagerCommission(managerCommission);
                    }
                }

            }
        }


    }

    @Override
    public Map<String, Object> selectCommissionSum(Map<String, String> parameter) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Map<String, String> map = commissionMapper.selectCommissionAllSum(parameter);
            String orderPriceSum = commissionMapper.selectCommissionDistinctSum(parameter);
            Object sellIndexObj = map.get("sellIndex");
            Object commissionObj = map.get("commission");
            Object orderPriceSumObj = orderPriceSum;
            resultMap.put("sellIndexSum", Integer.parseInt(sellIndexObj.toString()));
            resultMap.put("commissionSum", Integer.parseInt(commissionObj.toString()));
            resultMap.put("OrderPriceSum", Integer.parseInt(orderPriceSumObj.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }


    @Override
    public List<ManagerCommission> managerCommissionList(Map<String, String> map) {
        String payDate = map.get("payDate");
        if (StringUtils.isNotBlank(payDate)) {
            Date date = DateUtil.strToDate(payDate, DateUtil.DATE_TIME_YYYY_MM);
            map.put("payDate", DateUtil.dateToStr(date, DateUtil.DATE));
        }
        return managerCommissionMapper.selectManagerCommissionList(map);
    }

    @Override
    public void modifyManagerCommission(ManagerCommission managerCommission) {
        Map<String,String> map=new HashMap<>();
        map.put("sellerMonth",managerCommission.getSellerMonth());
        map.put("userOpenId",managerCommission.getUserOpenId());
        ManagerCommission   managerCommission1=    managerCommissionMapper.selectManagerCommission(map);
        Integer orderPrice=managerCommission.getOrderPrice();
        logger.info("orderPrice======>>>>"+orderPrice);
        //经理提成比例3.5%
        Integer commissionPrice=(orderPrice*35)/1000;
        logger.info("commissionPrice======>>>>"+commissionPrice);
        if(managerCommission1==null){
            managerCommission.setCommission(commissionPrice);
            insertManagerCommission(managerCommission);
            return;
        }
        Integer managerOrderPrice=managerCommission1.getOrderPrice()+orderPrice;
        managerCommission1.setOrderPrice(managerOrderPrice);

Integer managerCommissionPrice=managerCommission1.getCommission()+commissionPrice;

logger.info(managerOrderPrice+"<managerOrderPrice---------------------------------------------------managerCommissionPrice>"+managerCommissionPrice);
        managerCommission1.setCommission(managerCommissionPrice);
        updagteManagerCommission(managerCommission1);
    }

    private void insertManagerCommission(ManagerCommission managerCommission) {managerCommissionMapper.insertManagerCommission(managerCommission);
    }

    ;

    private void updagteManagerCommission(ManagerCommission managerCommission) {managerCommissionMapper.updateManagerCommissionByPrimaryKeySelective(managerCommission);
    }

    ;

    @Override
    public List<ManagerCommission> selectManagerCommissionList(Map<String, String> map) {
        String payDate = map.get("payDate");
        if(StringUtils.isBlank(payDate)){
            map.put("payDate", DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_YYYYMM));
        }

        return managerCommissionMapper.selectManagerCommissionList(map);
    }
}
